package com.dries.netty.chat.processer;

import cn.hutool.json.JSONUtil;
import com.dries.netty.chat.entity.User;
import com.dries.netty.chat.session.ServerSession;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 业务处理器
 * @author Dries
 * @email 1451691457@qq.com
 */
@Slf4j
public class ChatProcesser {

    /**
     * 单例
     */
    private static final ChatProcesser singleInstance = new ChatProcesser();

    public static ChatProcesser getSingleInstance() {
        return singleInstance;
    }

    /**
     * 连接建立成功调用的方法
     */
    public String onOpen(ServerSession session){
        Map<String, String> result = new HashMap<>();
        result.put("type", "bing");
        result.put("sendUser", "系统消息");
        result.put("id", session.getSessionId());

        return JSONUtil.toJsonStr(result);
    }

    /**
     * 连接关闭调用的方法
     */
    public String onClose(ServerSession session){
        User user = session.getUser();
        if (user != null) {
            return sendNotify(user);
        }
        return null;
    }

    /**
     * 收到消息后调用的方法
     */
    public Map<String, String> onMessage(String message, ServerSession session)
    {

        Map<String, String> map = JSONUtil.toBean(message, Map.class);
        Map<String, String> result = new HashMap<>();
        User user = null;
        switch (map.get("type"))
        {
            case "msg":
                user = session.getUser();
                result.put("type", "msg");
                result.put("msg", map.get("msg"));
                result.put("sendUser", user.getNickName());
                break;
            case "init":
                String room = map.get("room");
                session.setGroup(room);
                String nick = map.get("nick");
                user = new User(session.getSessionId(), nick);
                session.setUser(user);
                result.put("type", "init");
                result.put("msg", nick + "成功加入房间");
                result.put("sendUser", "系统消息");

                break;
            case "ping":
                break;
        }

        return result;
    }

    /**
     * 连接发生错误时的调用方法
     */
    public String onError(ServerSession session, Throwable error)
    {
        // 捕捉异常信息
        if (null != error)
        {
            log.error(error.getMessage());
        }

        User user = session.getUser();
        if (user == null)
        {
            return null;
        }
        return sendNotify(user);
    }

    private String sendNotify(User user) {
        String name = user.getNickName();

        Map<String, String> result = new HashMap<>();
        result.put("type", "init");
        result.put("msg", name + "离开房间");
        result.put("sendUser", "系统消息");

        return JSONUtil.toJsonStr(result);
    }

}
